﻿using HomagChina.CCHCS.ViewModels;
using Proxy;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Telerik.Windows.Controls;
using Telerik.Windows.DragDrop;
using ScrollViewer = System.Windows.Controls.ScrollViewer;

namespace HomagChina.CCHCS.Views
{
    /// <summary>
    /// JobList.xaml 的交互逻辑
    /// </summary>
    public partial class JobList : UserControl
    {
        private double HomeBatchDetailVerticalOffset;

        public JobList()
        {
            InitializeComponent();
            SubscripeToDragDropEvents();
        }

        private void SubscripeToDragDropEvents()
        {
            DragDropManager.AddDragInitializeHandler(JobTable, OnDragInitialize);
            DragDropManager.AddDropHandler(JobTable, OnDragOver);
        }

        public void ViewModel_RequestScrollPositionSave(object sender, EventArgs e)
        {
            SaveScrollPosition();
        }

        public void ViewModel_RequestScrollPositionRestore(object sender, EventArgs e)
        {
            RestoreScrollPosition();
        }

        private void SaveScrollPosition()
        {
            var BatchDetailscrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(JobTable);
            if (BatchDetailscrollViewer != null)
            {
                HomeBatchDetailVerticalOffset = BatchDetailscrollViewer.VerticalOffset;
            }
        }

        private void RestoreScrollPosition()
        {
            var BatchDetailscrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(JobTable);
            BatchDetailscrollViewer?.ScrollToVerticalOffset(HomeBatchDetailVerticalOffset);
        }

        public static class VisualTreeHelperExtensions
        {
            public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
            {
                if (parent == null) return null;

                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    if (child is T foundChild)
                    {
                        return foundChild;
                    }
                    var childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
                return null;
            }
        }

        private void OnDragInitialize(object sender, DragInitializeEventArgs e)
        {
            var radGridView = sender as RadGridView;
            var vm = DataContext as JobListViewModel;
            vm.SelectionMode = "Single";
            if (radGridView?.SelectedItem is JobModel item)
            {
                if (item.State == 1)
                {
                    e.AllowedEffects = DragDropEffects.None;
                    vm.SelectionMode = "Multiple";
                    return;
                }

                var dragPayload = DragDropPayloadManager.GeneratePayload(null);
                dragPayload.SetData("DraggedData", item);
                e.Data = dragPayload;

                e.DragVisual = new DragVisual()
                {
                    Content = item,
                    ContentTemplate = JobTable.Resources["DraggedItemTemplate"] as DataTemplate
                };

                e.DragVisualOffset = e.RelativeStartPoint;
                e.AllowedEffects = DragDropEffects.All;
            }

            e.Handled = true;
        }

        private void OnDragOver(object sender, Telerik.Windows.DragDrop.DragEventArgs e)
        {
            var source = e.OriginalSource as UIElement;
            var position = e.GetPosition(source);
            if (position != null)
            {
                var vm = DataContext as JobListViewModel;
                if (vm != null)
                {
                    var target = source.InputHitTest(position) as FrameworkElement;
                    if (target != null)
                    {
                        var targetData = target.DataContext as JobModel;
                        if (targetData != null)
                        {
                            var targetIndex = vm.List_JobInfoModel.IndexOf(targetData);
                            if (targetIndex != -1)
                            {
                                var draggedItem = DragDropPayloadManager.GetDataFromObject(e.Data, "DraggedData");
                                if (draggedItem != null)
                                {
                                    var draggedIndex = vm.List_JobInfoModel.IndexOf(draggedItem as JobModel);
                                    if (draggedIndex != -1)
                                    {
                                        if (targetIndex != draggedIndex && vm.List_JobInfoModel[draggedIndex].State != 20)
                                        {
                                            if (vm.List_JobInfoModel[targetIndex].State != 20)
                                            {
                                                vm.List_JobInfoModel.Move(draggedIndex, targetIndex);
                                                vm.DragExecute(vm.List_JobInfoModel);
                                            }
                                            else
                                            {
                                                HomagGroup.Base.UI.Windows.MessageBox.Show($"Sorry, you cannot move task '{vm.List_JobInfoModel[targetIndex].JobId}'in front of an active task!");
                                            }
                                            vm.SelectionMode = "Multiple";
                                        }
                                        else
                                        {
                                            HomagGroup.Base.UI.Windows.MessageBox.Show("Sorry, Cannot move tasks in progress!");
                                            vm.SelectionMode = "Multiple";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            e.Handled = true;
        }
    }
}